define(["./customDataShimJs", "rap"], function() {
    var app = require("app");

    function checkNull(obj) {
        if (obj == undefined || obj == null || obj == "" || obj.length <= 0)
            return true;
        return false;
    }

    app.filter('menuFilter', function() {
        return function(input, filterContent) {
            if (input == undefined || input == null || input.length <= 0)
                return;
            var newInput = [];
            for (var i = 0; i < input.length; i++) {
                if (input[i].name.indexOf(filterContent) != -1) {
                    newInput.push(input[i]);
                }
            }
            return newInput;
        }
    });

    app.controller("customDataCtrl", function($scope, $q, $location) {
        $scope.baseurl = "/api/rest/v3/workspaces/100/models/100/"; //表格获取数据的基本地址对象，双向绑定
        //过滤器对象与规则
        $scope.fdata={
            "rowFilter":[
                { "c_10001": /^[a-zA-Z]{0,5}$/ },
                { "c_10002": /^[a-zA-Z]{0,5}$/ },
            ],
            "columnFilter":/^name1|name2$/
        };
        $scope.zutable; //表格实例对象

        mainControlFunction();

        $scope.leftMenuItemClickEvent = function(item) {
            $scope.detailDivOpen = true;
            $location.search("modelId", item.id);
            //每次点击不同的模型，都会有对应的表格事件
            defineTable(item.name, 1, 0);
        }

        //给表格重新定义
        function defineTable(tablename, page, rowId) {
            $scope.zutable.defineTableName(tablename); //重新定义表格名称
            $scope.zutable.afterPageButtonClick(function() {
                $location.search("page", $scope.zutable.getNowPage());
            });
            $scope.zutable.afterTableItemClick(function() {
                $location.search("rowId", $scope.zutable.getNowSelectItem());
            });
            $scope.zutable.selectItem(rowId);
            $scope.zutable.gotoPointPage(page);
        }

        //根据url参数来渲染界面,最多判断50次
        function renderPageByUrlParams(count) {
            if (count > 50) {
                return;
            }
            //获取url路径中的参数集合,格式：{key1:value1,...}
            var inParams = $location.search();
            setTimeout(function() {
                $scope.$apply(function() {
                    //判断zutable是否已经有值
                    if (checkNull($scope.zutable)) {
                        renderPageByUrlParams(++count);
                        return;
                    }

                    //判断url中是否有模型id，modelid，再判断左侧模型列表中是否有对应的id
                    if (!checkNull(inParams.modelId)) {
                        var modelObj = $("div[data-id=_" + inParams.modelId + "]:eq(0)");
                        var modelActive = modelObj.attr("class");
                        var modelid = modelObj.attr("data-id");

                        if (!checkNull(modelid) && modelActive.indexOf("active", 0) == -1) {
                            modelObj.click();
                            //获取绑定的值，传递给绑定的angularjs的点击事件
                            var modelBindValue = angular.element(modelObj).inheritedData().$ngModelController.$modelValue;
                            $scope.detailDivOpen = true;
                            defineTable(modelBindValue.name, Number(inParams.page), Number(inParams.rowId));
                            // $scope.zutable.gotoPointPage(3);

                            return;
                        } else {
                            renderPageByUrlParams(++count);
                        }
                    }
                });
            }, 100);
        }

        function initVariable() {
            $scope.detailDivOpen = false; //数据模型详情div是否显示
            $scope.selectData = {}; //左侧菜单选中的数据模型对象
        }

        //主控函数
        function mainControlFunction() {
            loadLeftMenuList();
            // analyzeInParams(0);
            renderPageByUrlParams(0);
        }

        //加载左侧数据列表
        function loadLeftMenuList() {
            //从服务器加载数据
            var promise = myHttpHandler("GET", "/api/rest/v3/workspaces/" + 100 + "/models/", { "userId": 1 });
            promise.then(function(data) {
                if (data.result != 0) {
                    alert("模型数据加载异常");
                    return;
                }
                $scope.menuData = makeMenuData(data);
            });
        }

        //重新组织组织服务端数据
        function makeMenuData(data) {
            var tempData = data.data;
            var groups = []; //所有的分组对象,[{name:xxx,models:[]},{name:xxx,models:[]}]
            var groupsString = []; //所有分组的名字,[{name:xx,index:xx}],其中,index代表在groups里的索引下标

            for (var i = 0; i < tempData.length; i++) {
                var temp = tempData[i].groups.toString().split(",");
                for (var j = 0; j < temp.length; j++) {
                    var containIndex = judgeContains(groupsString, temp[j]);
                    if (containIndex == -1) { //如果不包含
                        groups[groups.length] = { name: temp[j], models: [] };
                        groups[groups.length - 1].models.push(tempData[i]);
                        groupsString[groupsString.length] = {};
                        groupsString[groupsString.length - 1].name = temp[j];
                        groupsString[groupsString.length - 1].index = groups.length - 1;
                    } else { //如果包含
                        groups[groupsString[containIndex].index].models.push(tempData[i]);
                    }
                }

            }

            return groups;
        }

        //判断数组中是否包含某个值(仅适用于makeMenuData())
        //不包含返回-1
        function judgeContains(array, string) {
            for (var i = 0; i < array.length; i++) {
                if (array[i].name == string) {
                    return i;
                }
            }
            return -1;
        }

        //左侧列表项点击事件
        $scope.menuItemClickEvent = function(cell) {
            initVariable();
            $scope.createDataObj = cell;
            LoadDetailTable();
            if ($scope.tableData.length <= 0) {
                $scope.detailDivOpen = false;
                $scope.createDivOpen = true;
            } else {
                $scope.detailDivOpen = true;
                $scope.createDivOpen = false;
            }
            $scope.selectData = cell;
        }

        $scope.menuListDeleteIconClickEvent = function(obj) {
            //传入id,删除模型,刷新界面
            var promise = myHttpHandler("DELETE", "/api/rest/v3/workspaces/100/models/" + obj, {});
            promise.then(function(data) {

                refreshMenuList();
            });

        }

        $scope.refreshClickEvent = function() {
            refreshMenuList();
        }

        function refreshMenuList() {
            initVariable();
            loadLeftMenuList();
        }

        function myHttpHandler(type, url, data) {
            var deferred = $q.defer();

            $.ajax({
                async: false,
                type: type,
                url: url,
                data: data,
                dataType: "json",
                error: function(responseData) {
                    alert("获取失败!");
                },
                success: function(responseData) {
                    deferred.resolve(responseData);
                    // console.log("return data="+responseData);
                }
            });

            return deferred.promise;
        }

    });
});
